/**
 * 打印执行报表
 */
var clivas = require('clivas');

function build(text, color, length) {
    return "{" + length + "+" + color + ":" + text + "}"
}
function formatnum(num) {
    var level = ["KB", "MB", "GB"]
    var val = num, levelnum = -1;
    while (levelnum++ < 3) {
        val = val / 1024;
        if (val < 1024)
            break;
    }

    return parseInt(val) + " " + level[levelnum];

}
function output() {

    var substats = {
        total: 0,
        totalspeed: 0,
        alive: 0,
        err: 0,
        ok: 0
    }

    clivas.clear(); // clears the canvas
    clivas.line('{15:#}{30:Rate}{30:Total}{15:Alive}{15:ok}{15:err}');
    clivas.line('========================================================================================================================');
    for (var x in stats) {
        substats.total += stats[x].totaldownload
        substats.totalspeed += stats[x].speed;
        substats.alive += parseInt(stats[x].alive);
        substats.ok += parseInt(stats[x].ok);
        substats.err += parseInt(stats[x].err);
        clivas.line(build(x, "yellow", 15) + build(formatnum(stats[x].speed), "green", 30)
            + build(formatnum(stats[x].totaldownload), "green", 30)
            + build(stats[x].alive, "green", 15) + build(stats[x].ok, "green", 15) + build(stats[x].err, "green", 15)
        );
    }
    clivas.line('');
    clivas.line('');
    clivas.line('');
    clivas.line(build("Total:", "yellow", 15) + build(formatnum(parseInt(substats.totalspeed)), "green", 30)
        + build(formatnum(substats.total), "green", 30)
        + build(substats.alive, "green", 15) + build(substats.ok, "green", 15) + build(substats.err, "green", 15)
    );

    var result = Object.keys(stats).every(function (x) {
        return stats[x].end
    })
    if (result == true) {
        clivas.line("执行完成");
        process.exit(0)
    }
}

var API = {
    start : function(data){
        stats = data;
        setInterval(output, 1000);
    }
}
module.exports = API